package com.zzstm.msmservice.service.impl;

import com.zzstm.msmservice.service.MsmService;
import com.zzstm.msmservice.utils.HttpUtils;
import com.zzstm.msmservice.utils.RandomUtil;
import com.zzstm.servicebase.ex.GuliException;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public String sendCode(String phone) {
        if (phone == null){
            System.err.println(phone);
            return null;
        }
        //调用地址：http(s)://jumsendsms.market.alicloudapi.com/sms/send-upgrade
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        //自己的appcode
        String appcode = "f9a0d9442ac64285b93151e40adb45bb";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        String code = RandomUtil.getFourBitRandom();
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("phone_number", phone);
        //使用服务商提供的测试模板id
        bodys.put("template_id", "TPL_0000");
        bodys.put("content", "code:" + code);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.err.println(response.toString());
            //获取response的body
            System.err.println(EntityUtils.toString(response.getEntity()));
            System.err.println(code);
            return code;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"短信发送失败");
        }

    }
}
